package aldy

import (
	"net/url"
	"strings"
	"xlq-demo/library/config"
	"github.com/google/uuid"
	"time"
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"net/http"
	"io/ioutil"
	"github.com/tidwall/gjson"
	"errors"
)

type SendIn struct {
	//手机号 多个逗号拼接
	Phone string
	//签名头
	SignName string
	//短信码
	TemplateCode string
	//参数 json
	TemplateParam string
}
func Send(in *SendIn) error {
	//组装参数
	//构建待签名字符串
	base := `AccessKeyId=`+specialUrlEncode(config.Config.Sms.AccessKeyId)+
		`&Action=`+specialUrlEncode("SendSms")+
		`&Format=`+specialUrlEncode("JSON")+
		`&PhoneNumbers=`+specialUrlEncode(in.Phone)+
		`&RegionId=`+specialUrlEncode("cn-hangzhou")+
		`&SignName=`+specialUrlEncode(in.SignName)+
		`&SignatureMethod=`+specialUrlEncode("HMAC-SHA1")+
		`&SignatureNonce=`+specialUrlEncode(getNonce())+
		`&SignatureVersion=`+specialUrlEncode("1.0")+
		`&TemplateCode=`+specialUrlEncode(in.TemplateCode)+
		`&TemplateParam=`+specialUrlEncode(in.TemplateParam)+
		`&Timestamp=`+specialUrlEncode(getTime())+
		`&Version=`+specialUrlEncode("2017-05-25")

	mBase := "GET&"+specialUrlEncode("/") + "&" + specialUrlEncode(base)

	//签名
	hmac := hmac.New(sha1.New,[]byte(config.Config.Sms.AccessKeySecret+"&"))
	hmac.Write([]byte(mBase))
	sign := base64.StdEncoding.EncodeToString(hmac.Sum(nil))

	sign = specialUrlEncode(sign)

	//返回公共参数
	commStr := "Signature="+sign+"&"+base

	url := "https://dysmsapi.aliyuncs.com?" + commStr

	//发起请求
	req,err := http.NewRequest("GET",url,nil)
	if err != nil {
		return err
	}

	client := &http.Client{}

	res,err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	//判断是否成功
	resBody,_ := ioutil.ReadAll(res.Body)

	resObj := gjson.ParseBytes(resBody)
	code := resObj.Get("Code").String()
	if code != "OK" {
		message := resObj.Get("Message").String()
		return errors.New("fail: " + code + "\n" + message)
	}
	return nil
}



//特殊url处理
func specialUrlEncode(s string) string {
	s = url.QueryEscape(s)
	s = strings.ReplaceAll(s,"+", "%20")
	s = strings.ReplaceAll(s,"*", "%2A")
	s = strings.ReplaceAll(s,"%7E", "~")
	return s
}

//获取随机字符串
func getNonce() string {
	return uuid.New().String()
}

//获取时间
func getTime() string {
	return time.Now().UTC().Format("2006-01-02T15:04:05Z")
}

